'use strict';
const db = uniCloud.database();
const unipay = require('unipay')
exports.main = async (event, context) => {
	switch (event.order_type) {
		case 0:
			return await create_order(event);
		case 1:
			return await look_order(event);
		case 2:
			return await close_order(event)
		case 8:
			return await or_list(event);
		case 9:
			return await isAliPay(event)
		case 10:
			return await isBanlanPay(event);
		case 11:
			return await isWeixinPay(event);
		case 12:
			return await pay_list(event);
		default:
			return {
				code: 200,
				msg: '暂未开发'
			}
	}
};

//创建订单
const create_order = async (event) => {
	delete event.order_type;
	let n_time = new Date(new Date().getTime()).getTime();
	event.create_time = n_time;
	event.effe_time = 86400000;
	event.end_time = (n_time + event.effe_time);
	event.coupon_id = "";
	event.integral = event.count_price - event.cou_price;
	event.pay_price = event.count_price - event.cou_price;
	//订单额外受益人id
	const user = db.collection('user');
	let res = await user.where({
		_id: event.user_detail.user_id
	}).get()
	event.rebate_user = res.data[0].invitecode;
	event.team_user = 0;
	event.status = 0;
	event.pay_status = 99;
	event.pay_time = "";
	//移除购物车的商品并且减去相应的库存
	for (let i in event.order_product) {
		let list0 = event.order_product[i].product_option.list0_name.split(':');
		let list1 = event.order_product[i].product_option.list1_name.split(':')
		// 删除相应的购物车
		if (event.order_product[i].create_cart) {
			let cart = db.collection('cart');
			let rescc = await cart.where({
				_id: event.order_product[i]._id
			}).get();
			if (rescc.data.length > 0) {
				cart.where({
					_id: event.order_product[i]._id
				}).remove();
			}
		}
		// 减去产品相应规格的库存
		let pro = db.collection('product_Detail');
		const poId = event.order_product[i].product_id;
		let stock = await pro.where({
			_id: poId
		}).get();
		stock = stock.data[0];
		// 相应产品中所有的规格
		let option = stock.product_option;
		for (let j in option) {
			for (let k in option[j].list) {
				if (j == 0) {
					if (option[j].list[k].list_desc == list0[0] && option[j].list[k].list_name == list0[1]) {
						let t_stock = parseInt(option[j].list[k].list_stock) - event.order_product[i].product_number;
						k = parseInt(k);
						pro.where({
							_id: poId
						}).update({
							product_option: {
								0: {
									list: {
										[k]: {
											list_stock: t_stock
										}
									}
								}
							}
						})
					}
				} else {
					if (list1.length > 1) {
						if (option[j].list[k].list_desc == list1[0] && option[j].list[k].list_name == list1[1]) {
							let t_stock = parseInt(option[j].list[k].list_stock) - event.order_product[i].product_number;
							k = parseInt(k);
							pro.where({
								_id: poId
							}).update({
								product_option: {
									1: {
										list: {
											[k]: {
												list_stock: t_stock
											}
										}
									}
								}
							})
						}
					}
				}
			}
		}
	}
	let order = db.collection('order');
	let create = await order.add(event);
	//订单所属团队id
	return create


	// 支付问题




	// return orderInfo
}

//关闭订单
const close_order = async (event) => {
	let order = db.collection('order');
	let res = await order.where({
		_id: event.order_id
	}).update({
		status: 99
	});
	return res
}

//查看指定用户下的特定状态的订单
const or_list = async (event) => {
	let or = db.collection('order');
	if (event.status == 99) {
		let res = await or.where({
			user_detail: {
				user_id: event.user_id
			}
		}).orderBy('create_time', 'desc').skip(event.pageNum * event.pageSize).limit(event.pageSize).get();
		return res
	} else {
		let res = await or.where({
			user_detail: {
				user_id: event.user_id
			},
			status: event.status
		}).orderBy('create_time', 'desc').skip(event.pageNum * event.pageSize).limit(event.pageSize).get();
		return res
	}
}

//查看单个订单
const look_order = async (event) => {
	let or = db.collection('order');
	let res = or.where({
		_id: event.order_id
	}).get();
	return res
}

//返回支付列表
const pay_list = async (event) => {
	//查询订单是否有效
	let order = db.collection('order');
	let or_de = await order.where({
		_id: event.order_id
	}).count();
	if (or_de.total == 1) {
		let or_deta = await order.where({
			_id: event.order_id
		}).get();
		let er = or_deta.data[0];
		let ed_time = new Date(er.end_time).getTime();
		let n_time = new Date().getTime() + 28800000;
		if (ed_time - n_time >= 0) {
			const pay_li = db.collection('pay_list');
			let res = await pay_li.where({
				pay_status: 1
			}).get();
			return res
		} else {
			let or_deta = order.where({
				_id: event.order_id
			}).update({
				status: 99
			});
			return {
				code: 200,
				msg: "订单已失效"
			}
		}
	} else {
		return {
			code: 200,
			msg: "查到一个或多个订单"
		}
	}
}

//发起余额支付
const isBanlanPay = async (event) => {
	let order = db.collection('order');
	let user = db.collection('user');
	let or_de = await order.where({
		_id: event.order_id
	}).get();
	or_de = or_de.data[0];
	let us = await user.where({
		_id: or_de.user_detail.user_id
	}).get();
	us = us.data[0];
	let or_price = or_de.pay_price;
	let us_price = us.balance;
	if (us_price < or_price) {
		return {
			code: 200,
			msg: '余额不足'
		}
	} else {
		//计算得到用户之前的总共购买积分和购买后的积分
		let us_int = us.integral;
		let ush = us.shopIntegral
		let or_int = or_de.integral;

		//计算得到用户之前的总共购买金额和购买后的金额
		let us_shBala = us.shopBalance;
		let usn_balace = us_price - or_price;
		let usn_shBala = us_shBala + or_price;

		//更新用户余额和积分
		user.where({
			_id: or_de.user_detail.user_id
		}).update({
			balance: usn_balace,
			shopBalance: usn_shBala,
			integral: us_int + or_int,
			shopIntegral: ush + or_int
		});

		let now_time = new Date().getTime();
		const balace_list = db.collection('balace_list');
		let params = {
			"type": 1,
			"desc": `购买了订单${event.order_id}的商品`,
			"cerate_time": now_time,
			"num": or_price,
			"user_id": or_de.user_detail.user_id
		}
		// 加入余额记录
		balace_list.add(params);

		const sign = db.collection('sign_in_user');
		let sign_pa = {
			user_id: or_de.user_detail.user_id,
			integral_number: or_int,
			sign_time: now_time,
			type: 2,
			descration: `购买了订单${event.order_id}的商品`
		}
		sign.add(sign_pa);
		//更新订单状态返回给前端
		let result = await order.where({
			_id: event.order_id
		}).update({
			status: 1,
			pay_status: 1,
			pay_time: now_time
		});
		return result
	}
}

//微信支付参数
const isWeixinPay = async (event) => {
	let pay_lists = db.collection('pay_list');
	let cc = await pay_lists.get();
	let unipayIns = unipay.initWeixin({
		appId: cc.data[0].appid,
		mchId: cc.data[0].mchId,
		key: cc.data[0].key
	})
	let order = db.collection('order');
	let res = await order.where({
		_id: event.order_id
	}).get();
	let orderInfo = await unipayIns.getOrderInfo({
		body: res.data[0]._id,
		outTradeNo: res.data[0]._id,
		totalFee: res.data[0].pay_price * 100,
		notifyUrl: "http://api9006d.tatagogo.com/api",
		tradeType: "APP"
	})
	return orderInfo
}

//支付宝支付
const isAliPay = async (event) => {
	let pay_lists = db.collection('pay_list');
	let cc = await pay_lists.get();
	let unipayIns = unipay.initAlipay({
		appId: cc.data[2].appid,
		mchId: cc.data[2].mchId,
		privateKey: cc.data[2].key
	})
	let order = db.collection('order');
	let res = await order.where({
		_id: event.order_id
	}).get();
	let orderInfo = await unipayIns.getOrderInfo({
		subject: res.data[0]._id,
		outTradeNo: res.data[0]._id,
		totalFee: 1,
		// totalFee: res.data[0].pay_price * 100,
		notifyUrl: cc.data[2].notifyUrl,
		tradeType: "APP"
	})
	return orderInfo
}
